package com.shxc.smarttrade.old.foreignfragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.github.mikephil.charting.utils.Utils;
import com.shxc.smarttrade.R;
import com.shxc.smarttrade.quotation.old.AllQuotationActivity;
import com.shxc.smarttrade.old.activity.RechargeActivity;
import com.shxc.smarttrade.old.bean.EventDatas;
import com.shxc.smarttrade.old.bean.OpenTrader;
import com.shxc.smarttrade.old.bean.PendingOrder;
import com.shxc.smarttrade.old.bean.RealTimeQuoteDatas;
import com.shxc.smarttrade.old.bean.StockChartDatas;
import com.shxc.smarttrade.old.bean.SymbolInfo;
import com.shxc.smarttrade.old.bean.SymbolPrice;
import com.shxc.smarttrade.old.constants.EventContents;
import com.shxc.smarttrade.old.iview.ISimpleTradeFragment;
import com.shxc.smarttrade.old.myview.MyProgressDialog;
import com.shxc.smarttrade.old.presenter.SimpleTradePresenter;
import com.shxc.smarttrade.old.utils.Arith;
import com.shxc.smarttrade.old.utils.BaseUtils;
import com.shxc.smarttrade.old.utils.CountClass;
import com.shxc.smarttrade.old.utils.Logger;
import com.shxc.smarttrade.old.utils.SpUtils;
import com.shxc.smarttrade.utils.Loger;
import com.umeng.analytics.MobclickAgent;
import com.wordplat.ikvstockchart.InteractiveKLineView;
import com.wordplat.ikvstockchart.drawing.HighlightDrawing;
import com.wordplat.ikvstockchart.drawing.MACDDrawing;
import com.wordplat.ikvstockchart.drawing.StockIndexYLabelDrawing;
import com.wordplat.ikvstockchart.entry.Entry;
import com.wordplat.ikvstockchart.entry.EntrySet;
import com.wordplat.ikvstockchart.entry.StockMACDIndex;
import com.wordplat.ikvstockchart.marker.XAxisTextMarkerView;
import com.wordplat.ikvstockchart.marker.YAxisTextMarkerView;
import com.wordplat.ikvstockchart.render.KLineRender;
import com.wordplat.ikvstockchart.render.TimeLineRender;
import com.zhy.autolayout.AutoLinearLayout;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.buildins.UIUtil;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView;

import org.greenrobot.eventbus.EventBus;
import org.xchris.x;

import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;


/**
 * Created by jcdev1 on 2017/10/27.
 */

public class SimpleTransFragment extends Fragment implements ISimpleTradeFragment {

    @BindView(R.id.tv_ch_name)
    TextView tvChName;
    @BindView(R.id.tv_cn_name)
    TextView tvCnName;
    @BindView(R.id.tv_mark_price)
    TextView tvMarkPrice;
    @BindView(R.id.tv_price_var)
    TextView tvPriceVar;
    @BindView(R.id.tv_rate_of_change)
    TextView tvRateOfChange;
    @BindView(R.id.magic_indicator)
    MagicIndicator magicIndicator;
    @BindView(R.id.iv_arrow_right)
    ImageView ivArrowRight;
    TextView StockIndexText;
    @BindView(R.id.k_line)
    InteractiveKLineView kLine;
    @BindView(R.id.tv_account)
    TextView tvAccount;
    @BindView(R.id.tv_margin)
    TextView tvMargin;
    @BindView(R.id.tv_margin_account)
    TextView tvMArginAccount;
    @BindView(R.id.no_iv_left_sub)
    ImageView noIvLeftSub;
    @BindView(R.id.no_tv_center_times)
    EditText noTvCenterTimes;
    @BindView(R.id.no_iv_right_add)
    ImageView noIVRightAdd;
    @BindView(R.id.ll_one)
    AutoLinearLayout llOne;
    @BindView(R.id.tv_real_rise)
    TextView tvRealRise;
    @BindView(R.id.ll_buy_rise)
    AutoLinearLayout llBuyRise;
    @BindView(R.id.tv_real_fall)
    TextView tvRealFall;
    @BindView(R.id.tv_spread)
    TextView tvSpread;
    @BindView(R.id.tv_lines)
    TextView tvLines;
    @BindView(R.id.tv_margin_text)
    TextView tvMarginText;

    @BindView(R.id.rl_buy_status)
    RelativeLayout rlBuyStatus;

    private View rootView;

    private boolean isGetKData = false;//判断是否获取到K线图数据
    private List<StockChartDatas.DataBean.QuotesBean> qb;
    private long oldTime;//报价时间
    private double oldOpenPrice;//开盘价（某个时间段的）
    private double oldHigt;//最高价（某个时间段的）
    private double oldLow;//最低价（某个时间段的）
    private double oldClose;//收盘价（某个时间段的）
    private int realDataSize = 0;//真实K线图或分时图集合大小
    private int timeLineTag = 0;//用于判断是日分时还是分时 0：日分时 1:分k线图 2：日K图
    private boolean isKLine = false;//当前展示的是否为K线图
    private int digits = 5;//价格小数位数
    private int oldPosition = 0;//记录当前K线所属
    private long timeDiff;//记录不同时间差
    private MyProgressDialog shortDialog;
    private String symbolK;
    private AllQuotationActivity activity;
    private double yestodayClosePrice = -1;//昨日收盘价

    private double noPendingTimes;//购买手数（待提交参数volume）
    private double minVolume;//手数每次减少和增加的量
    private String[] symbols = null;//保证金和盈亏计算所需要的不同品种英文名称
    private double[] askBidOne = null;
    private double[] askBidTwo = null;
    private double[] askBidThree = null;
    private double stopsLevel;//止盈止损远离步长
    private double stopLossOrProfitVar;//止盈止损的变化量
    private double stopLossTotal;//止损处总的改变量
    private double stopProfitTotal;//止盈处总的改变量
    private int type;//当前项目类型
    private double marginBase;//占用保证金计算基数
    private boolean marginChange = false;//保证金是否要转化成美元
    private boolean profitChange = false;//盈亏是否要转化成美元
    private boolean profitUSDPrex = false;//盈亏是否已美元为基础货币
    private boolean usdprex = false;//保证金是否已美元为基础货币
    private int contracSize;//合约数
    private double accAmt;//账户余额
    public int selectWhatNoPended = 0;//未开启挂单选择买入还是卖出 0：买入 1：卖出
    private String buyMax;//最大可买手数拼接的字符串
    private double handMax;//最大可买手数
    private double marginAll;//保证金总数
    private double ask;//实时买价
    private double bid;//实时卖价
    private double sl = 0;//待提交参数（止损价）
    private double tp = 0;//待提交参数（止盈价）
    private PopupWindow popupWindow;
    private Handler handler = new Handler();
    private Runnable runnable;
    private boolean isFinishActivity = false;//是否在popupWindow消失时关闭Activity
    private int showTime = 5000;
    private boolean quickOrderStatus = false;//是否快捷开仓

    private static final String[] tabName = {"分时", "日线", "周线", "1分钟", "5分钟", "15分钟", "30分钟", "1小时", "4小时", "月线"};
    private List<String> mDataList = Arrays.asList(tabName);

    private SimpleTradePresenter presenter;
    private String accessToken = "";
    private boolean dealSwitch = false;

    private SoundPool soundPool;//声明一个SoundPool

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        if (rootView == null) {
            rootView = inflater.inflate(R.layout.simple_trans_fragment, null);
        }
        //缓存的rootView需要判断是否已经被加过parent， 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        ButterKnife.bind(this, rootView);
//        EventBus.getDefault().register(this);
        initView();
        initSound();
        initData();
        return rootView;
    }

    @SuppressLint("NewApi")
    private void initSound() {
        soundPool = new SoundPool.Builder().build();
    }

    private void initData() {
        activity = (AllQuotationActivity) getActivity();//第一行
        digits = activity.digits;
        accessToken = SpUtils.getString(getActivity(), "accessToken", "");
        quickOrderStatus = SpUtils.getBoolean(getActivity(), "quickOrderStatus", false);
        dealSwitch = SpUtils.getBoolean(getActivity(), "dealSwitch", false);

        rlBuyStatus.setVisibility(View.VISIBLE);
//        if (dealSwitch) {
//            rlBuyStatus.setVisibility(View.VISIBLE);
//        } else {
//            rlBuyStatus.setVisibility(View.GONE);
//        }
        presenter = new SimpleTradePresenter(this);
        timeDiff = 1000 * 60;
        symbolK = activity.symbleOne;//用于请求K线图的产品名称
        tvChName.setText(activity.symbolCn);
        tvCnName.setText(activity.symbleOne);
        presenter.getStockChartData(accessToken, symbolK, "0", 0);

    }

    private void initView() {

        initMagicIndicator();
        initListener();
    }


    /**
     * 初始化指示器
     */
    private void initMagicIndicator() {
        final CommonNavigator commonNavigator = new CommonNavigator(getActivity());
        commonNavigator.setRightPadding(UIUtil.dip2px(getActivity(), 40));
        commonNavigator.setScrollPivotX(0.25f);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return mDataList == null ? 0 : mDataList.size();
            }

            @Override
            public IPagerTitleView getTitleView(final Context context, final int i) {
                final SimplePagerTitleView clipPagerTitleView = new SimplePagerTitleView(context);
                clipPagerTitleView.setText(mDataList.get(i));
                clipPagerTitleView.setNormalColor(Color.parseColor("#666666"));
                clipPagerTitleView.setSelectedColor(Color.parseColor("#36436a"));
                clipPagerTitleView.setTextSize(BaseUtils.dip2px(context, 4.5f));
                clipPagerTitleView.setPadding(BaseUtils.dip2px(context, 16.0f), 0, BaseUtils.dip2px(context, 16.0f), 0);

                clipPagerTitleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (i == oldPosition) return;
                        oldPosition = i;
                        commonNavigator.onPageSelected(i);
                        commonNavigator.onAttachToMagicIndicator();
                        int position = i;
                        if (position == 0) {
                            isKLine = false;
                            showDialog();
                            timeLineTag = 0;
                            timeDiff = 1000 * 60;
                            presenter.getStockChartData(accessToken, symbolK, "0", 0);
                            MobclickAgent.onEvent(getContext(), "day_time");//友盟统计该点击事件发生次数
                        } else if (position == 1) {
                            isKLine = true;
                            showDialog();
                            timeLineTag = 2;
                            timeDiff = 1000 * 60 * 60 * 24;
                            presenter.getStockChartData(accessToken, symbolK, "1440", 0);
                            MobclickAgent.onEvent(getContext(), "one_day_k");//友盟统计该点击事件发生次数
                        } else if (position == 2) {
                            isKLine = true;
                            timeLineTag = 1;
                            showDialog();
                            timeDiff = 1000 * 60 * 60 * 24 * 7;
                            presenter.getStockChartData(accessToken, symbolK, "10080", 0);

                            MobclickAgent.onEvent(getContext(), "one_minute_k");//友盟统计该点击事件发生次数
                        } else if (position == 3) {
                            isKLine = true;
                            showDialog();
                            timeLineTag = 1;
                            timeDiff = 1000 * 60;
                            presenter.getStockChartData(accessToken, symbolK, "1", 0);
                            MobclickAgent.onEvent(getContext(), "five_minute_k");//友盟统计该点击事件发生次数
                        } else if (position == 4) {
                            isKLine = true;
                            showDialog();
                            timeLineTag = 1;
                            timeDiff = 1000 * 60 * 5;
                            presenter.getStockChartData(accessToken, symbolK, "5", 0);

                            MobclickAgent.onEvent(getContext(), "fifteen_minute_k");//友盟统计该点击事件发生次数
                        } else if (position == 5) {
                            isKLine = true;
                            timeLineTag = 1;
                            showDialog();
                            timeDiff = 1000 * 60 * 15;
                            presenter.getStockChartData(accessToken, symbolK, "15", 0);
                            MobclickAgent.onEvent(getContext(), "thirteen_minute_k");//友盟统计该点击事件发生次数
                        } else if (position == 6) {
                            isKLine = true;
                            timeLineTag = 1;
                            showDialog();
                            timeDiff = 1000 * 60 * 30;
                            presenter.getStockChartData(accessToken, symbolK, "30", 0);

                        } else if (position == 7) {
                            isKLine = true;
                            timeLineTag = 1;
                            showDialog();
                            timeDiff = 1000 * 60 * 60;
                            presenter.getStockChartData(accessToken, symbolK, "60", 0);

                        } else if (position == 8) {
                            isKLine = true;
                            timeLineTag = 1;
                            showDialog();
                            timeDiff = 1000 * 60 * 60 * 4;
                            presenter.getStockChartData(accessToken, symbolK, "240", 0);

                        } else if (position == 9) {
                            isKLine = true;
                            timeLineTag = 1;
                            showDialog();
                            timeDiff = 1000 * 60 * 60 * 24 * 10;
                            presenter.getStockChartData(accessToken, symbolK, "43200", 0);
                        }
                    }
                });

                return clipPagerTitleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
                LinePagerIndicator indicator = new LinePagerIndicator(context);
                indicator.setColors(new Integer[]{Color.parseColor("#36436a")});
                indicator.setMode(LinePagerIndicator.MODE_EXACTLY);
                indicator.setLineHeight(BaseUtils.dip2px(context, 2));

                return indicator;
            }
        });
        magicIndicator.setNavigator(commonNavigator);
    }

    /**
     * 昨收、今开、最高、最低
     *
     * @param symbolPrice
     */
    public void setBaseData(SymbolPrice symbolPrice) {
        yestodayClosePrice = symbolPrice.getYesterdayClosePrice();
    }

    /**
     * 监听手数的文本输入
     */
    private void initListener() {
        noTvCenterTimes.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                //限制最大值和最小值
                String text = s.toString();
                int dotIndex = text.indexOf(".");
                int textLength = text.length();

                if (dotIndex == 0) {
//                    tvMargin.setText("手数格式错误");
                    return;
                }
                if (textLength - 1 == dotIndex) {
                    text = text + "00";
                }
                if (textLength - dotIndex > 3) {
                    text = text.substring(0, dotIndex + 3);
//                    tvMargin.setText("只保留小数点后两位");
                }
                double handtimes = Double.parseDouble(text);
                if (handtimes < 0.01) {
//                    tvMargin.setText("最小0.01手");
                    noPendingTimes = 0.01;
                    return;
                }
                if (handtimes > handMax) {
//                    tvMargin.setText("最大" + handMax + "手");
                    noPendingTimes = handMax;
                    return;
                }
                noPendingTimes = handtimes;

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        noTvCenterTimes.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    InputMethodManager im = (InputMethodManager) getActivity().getSystemService(getContext().INPUT_METHOD_SERVICE);
                    im.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                }
            }
        });

//        ((StockChartUpgradeActivity) getActivity()).llAll.setOnSoftKeybordStatusListener(new CommonAutoRelativeLayout.softKeybordStatusListener() {
//            @Override
//            public void softKeybordStatus(boolean status) {
//
//                if (status) {
//                    noTvCenterTimes.setCursorVisible(true);
//                } else {
//                    noTvCenterTimes.setCursorVisible(false);
//                }
//            }
//        });
    }

    /**
     * 盈亏计算及品种保证金相关数据
     *
     * @param symbolInfo
     */
    public void setSymbolCalInfoDatas(SymbolInfo symbolInfo) {
        if (symbolInfo.getAccType() == 1) {
            tvAccount.setText("TigerWit（" + symbolInfo.getMt4Id() + "）");
            tvMArginAccount.setText("$" + symbolInfo.getAccAmt());
        } else if (symbolInfo.getAccType() == 0) {
            tvMArginAccount.setText("$" + symbolInfo.getAccAmt());
            tvAccount.setText("SmartTrade（模拟账户）");
        } else {
            tvMArginAccount.setVisibility(View.GONE);
            tvLines.setVisibility(View.GONE);
            tvMarginText.setVisibility(View.GONE);
            tvAccount.setText("立即注册，领$1000体验金。");
        }


        if (symbolInfo != null) {
            if (noTvCenterTimes == null) return;
            noTvCenterTimes.setText(symbolInfo.getMinVolume() + "");
            symbols = new String[]{symbolK, symbolInfo.getMarginCalCurrency(), symbolInfo.getProfitCalCurrency()};
            minVolume = symbolInfo.getMinVolume();
            noPendingTimes = symbolInfo.getMinVolume();
            double stopsLe = (double) symbolInfo.getStopsLevel();
            digits = symbolInfo.getDigits();
            stopsLevel = Arith.div(stopsLe, Math.pow(10, digits), digits);
            double dd = Math.pow(10, digits);
            stopLossOrProfitVar = Arith.round3(Arith.div(1, dd), digits);
            type = symbolInfo.getType();
            marginBase = symbolInfo.getMarginBase();
            marginChange = symbolInfo.isMarginChange();
            profitChange = symbolInfo.isProfitChange();
            profitUSDPrex = symbolInfo.isProfitUSDPrex();
            usdprex = symbolInfo.isUsdprex();
            contracSize = symbolInfo.getContractSize();
            accAmt = symbolInfo.getAccAmt();
        }
    }

    /**
     * 接收实时价格
     *
     * @param quoteBeen
     */
    public void setRealPrice(List<RealTimeQuoteDatas.DataBean.QuoteBean> quoteBeen) {
        if (getActivity() == null) return;
        setRealTimeDatas(quoteBeen);
        /**
         *实时价格及其变化率
         */

        if (yestodayClosePrice != -1) {
            double d1 = Arith.sub(quoteBeen.get(0).getMarket(), yestodayClosePrice);
            double d2 = Arith.mul(Arith.div(d1, yestodayClosePrice, 5), 100.0);
            if (d1 > 0) {
                tvPriceVar.setTextColor(getResources().getColor(R.color.stock_rise_color));
                tvRateOfChange.setTextColor(getResources().getColor(R.color.stock_rise_color));
                tvRateOfChange.setText("+" + BaseUtils.getDigitsData(d2, 2) + "%");
                tvPriceVar.setText("+" + BaseUtils.getDigitsData(d1, digits == -1 ? 2 : digits));

            } else {
                tvPriceVar.setTextColor(getResources().getColor(R.color.stock_fell_color));
                tvRateOfChange.setTextColor(getResources().getColor(R.color.stock_fell_color));
                tvRateOfChange.setText(BaseUtils.getDigitsData(d2, 2) + "%");
                tvPriceVar.setText(BaseUtils.getDigitsData(d1, digits == -1 ? 2 : digits));
            }
        }

        /**
         * 实时修改k线图数据
         */

        Long newTime = quoteBeen.get(0).getTime();
        String n1 = BaseUtils.getDateFromMillionSeconds(newTime);
        newTime = BaseUtils.getMillionSecondsFromDate(n1);
        Double market = quoteBeen.get(0).getMarket();
        String newData = BaseUtils.millionToDate(quoteBeen.get(0).getTime());
        tvRealRise.setText(BaseUtils.getDigitsData(quoteBeen.get(0).getAsk(), digits));
        tvRealFall.setText(BaseUtils.getDigitsData(quoteBeen.get(0).getBid(), digits));
        tvSpread.setText(Arith.format(quoteBeen.get(0).getAsk(), quoteBeen.get(0).getBid(), digits));
        tvMarkPrice.setText(BaseUtils.getDigitsData(quoteBeen.get(0).getMarket(), digits));
//        tvRealTime.setText(BaseUtils.getDigitsData(quoteBeen.get(0).getMarket(), digits));

        if (newTime - oldTime < timeDiff) {
            oldHigt = Math.max(market, oldHigt);
            oldLow = Math.min(market, oldLow);
            oldClose = market;
            //更改最后一个数据
            changeLastData(newData, quoteBeen.get(0).getTime());
        } else {

            oldTime = newTime;
            oldOpenPrice = market;
            oldHigt = market;
            oldLow = market;
            oldClose = market;

            if (timeLineTag == 0) {
                presenter.getStockChartData(accessToken, symbolK, "0", 1);
            } else {
                //增加一条K线图新数据
                EntrySet entrySett = new EntrySet();
                entrySett.addEntry(new Entry((float) oldOpenPrice, (float) oldHigt, (float) oldLow, (float) oldClose, 0, newData));

                entrySett.computeStockIndex();
                List<Entry> entriess = entrySett.getEntryList();
                kLine.getRender().getEntrySet().addEntries(entriess);
                kLine.notifyDataSetChanged();
            }
        }
    }

    /**
     * 实时更改最后一条数据
     *
     * @param newData
     */
    private void changeLastData(String newData, long newDate2) {
        EntrySet entrySets = new EntrySet();
        List<Entry> en = kLine.getRender().getEntrySet().getEntryList();
        if (timeLineTag == 0) {
            if (realDataSize > 0 && en.size() > 1) {
                if (en.size() >= realDataSize)
                    en.remove(realDataSize - 1);
                en.add(realDataSize - 1, new Entry((float) oldOpenPrice, (float) oldHigt, (float) oldLow, (float) oldClose, 0, String.valueOf(newDate2)));
            }
        } else {
            if (realDataSize > 0 && en.size() > 1) {
                en.remove(en.size() - 1);
                en.add(new Entry((float) oldOpenPrice, (float) oldHigt, (float) oldLow, (float) oldClose, 0, newData));
            }
        }

        entrySets.addEntries(en);
        entrySets.computeStockIndex();
        kLine.setEntrySet(entrySets);
        kLine.notifyDataSetChanged();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void showDialog() {
        if (shortDialog == null && getActivity() != null) {
            shortDialog = new MyProgressDialog(getActivity());
            shortDialog.setCancelable(false);
        }
        shortDialog.show();
    }

    @Override
    public void dismissDialog() {
        if (shortDialog != null && getActivity() != null)
            shortDialog.dismiss();

    }

    @Override
    public void showMyToast(String str) {
        if (getActivity() != null)
            Toast.makeText(getActivity(), str, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void setStockChartData(StockChartDatas stockChartDatas) {

        if (getActivity() == null) {
            Loger.e("ca","!!!!");
            return;
        }

        isGetKData = true;
        qb = stockChartDatas.getData().getQuotes();
        int qbSize = qb.size();
        if (tvRealRise == null) return;
        if (qb == null || qb.size() == 0) return;
//                        Collections.reverse(qb);
        oldTime = qb.get(qb.size() - 1).getTime();
        String d1 = BaseUtils.getDateFromMillionSeconds(oldTime);
        oldTime = BaseUtils.getMillionSecondsFromDate(d1);

        oldOpenPrice = qb.get(qb.size() - 1).getOpenPrice();
        oldHigt = qb.get(qb.size() - 1).getHigh();
        oldLow = qb.get(qb.size() - 1).getLow();
        oldClose = qb.get(qb.size() - 1).getClose();
        tvRealRise.setText(BaseUtils.getDigitsData(qb.get(qb.size() - 1).getClose(), digits));
        tvRealFall.setText(BaseUtils.getDigitsData(qb.get(qb.size() - 1).getOpenPrice(), digits));

        EntrySet entrySet = new EntrySet();

//        final int stockMarkerViewHeight = BaseUtils.dip2px(getActivity(), 15);
        final int stockMarkerViewHeight = BaseUtils.dip2px(getActivity().getBaseContext(), 15);
        realDataSize = qbSize;
        for (int i = 0; i < qb.size(); i++) {
            Long dataStr = qb.get(i).getTime();
            if (timeLineTag == 0)
                entrySet.addEntry(new Entry((float) qb.get(i).getOpenPrice(), (float) qb.get(i).getHigh(), (float) qb.get(i).getLow(), (float) qb.get(i).getClose(), qb.get(i).getVol(), dataStr + ""));
            else {
                String data = "";
                if (timeLineTag == 1) {
                    data = BaseUtils.millionToMinute(dataStr);
                } else {
                    data = BaseUtils.millionToDay(dataStr);
                }
                entrySet.addEntry(new Entry((float) qb.get(i).getOpenPrice(), (float) qb.get(i).getHigh(), (float) qb.get(i).getLow(), (float) qb.get(i).getClose(), qb.get(i).getVol(), data + ""));
            }
        }
        if (timeLineTag == 0) {
            for (int i = 0; i < 1440 - qbSize; i++)
                entrySet.addEntry(new Entry((float) qb.get(qbSize - 1).getOpenPrice(), (float) qb.get(qbSize - 1).getHigh(), (float) qb.get(qbSize - 1).getLow(), (float) qb.get(qbSize - 1).getClose(), qb.get(qbSize - 1).getVol(), 0 + ""));

        } else if (timeLineTag == -1) {
            for (int i = 0; i < 480 - qbSize; i++)
                entrySet.addEntry(new Entry((float) qb.get(qbSize - 1).getOpenPrice(), (float) qb.get(qbSize - 1).getHigh(), (float) qb.get(qbSize - 1).getLow(), (float) qb.get(qbSize - 1).getClose(), qb.get(qbSize - 1).getVol(), 0 + ""));
        }
        int intDigit = 0;
        if (qb.size() > 0) {
            String str = String.valueOf(qb.get(0).getClose());
            int index = str.indexOf(".");
            if (index != -1) {
                intDigit = index + 1;
            }

        }
        if (isKLine) {//K线图数据
            kLine.setRender(new KLineRender(getActivity(), digits, intDigit));
            entrySet.computeStockIndex();//计算其它附带指标
            kLine.setEntrySet(entrySet);
            KLineRender kr = (KLineRender) kLine.getRender();

            // MACD
            HighlightDrawing macdHighlightDrawing = new HighlightDrawing();
            macdHighlightDrawing.addMarkerView(new YAxisTextMarkerView((int) Utils.convertDpToPixel(10), digits));

            StockMACDIndex macdIndex = new StockMACDIndex();
            macdIndex.addDrawing(new MACDDrawing());
            macdIndex.addDrawing(new StockIndexYLabelDrawing());
            macdIndex.addDrawing(macdHighlightDrawing);
            macdIndex.setPaddingTop((int) Utils.convertDpToPixel(10));
            kr.addStockIndex(macdIndex);

            //下面两行代码可以控制十字线两端是否有文本展示
            kr.addMarkerView(new YAxisTextMarkerView(stockMarkerViewHeight, digits));
            kr.addMarkerView(new XAxisTextMarkerView(stockMarkerViewHeight));


        } else {//分时图数据
            kLine.setRender(new TimeLineRender(timeLineTag, realDataSize, digits, intDigit));
            entrySet.computeStockIndex();
            kLine.setEntrySet(entrySet);
            TimeLineRender tr = (TimeLineRender) kLine.getRender();

            tr.addMarkerView(new YAxisTextMarkerView(stockMarkerViewHeight, digits));
            tr.addMarkerView(new XAxisTextMarkerView(stockMarkerViewHeight));
        }
        kLine.notifyDataSetChanged();
    }

    @Override
    public void setTradeBackInfo(OpenTrader openTrader) {
        setPopupTraderOpenSuccess(openTrader);
    }

    @Override
    public void setPendingBackInfo(PendingOrder pendingOrder) {

    }


    /**
     * 交易手数 减
     */
    @OnClick(R.id.no_iv_left_sub)
    public void noIVLeftSub() {
        Logger.e("Test", "-------");
        if (noPendingTimes > minVolume) {
            noPendingTimes = Arith.sub(noPendingTimes, minVolume);
            noTvCenterTimes.setText(noPendingTimes + "");
            double margin = CountClass.getMargin(type, noPendingTimes, askBidOne, askBidTwo, selectWhatNoPended, marginBase, marginChange, usdprex);
            if (margin == -1) return;
            tvMargin.setText("占用保证金:$" + margin + "美金");
            marginAll = margin;
        }

    }

    /**
     * 交易手数 加
     */
    @OnClick(R.id.no_iv_right_add)
    public void noIVRightAdd() {
        //先判断可买的最大手数，当满足条件后才执行下面操作
        Logger.e("Test", "++++++++");
        if (noPendingTimes < handMax) {
            noPendingTimes = Arith.add(noPendingTimes, minVolume);
            noTvCenterTimes.setText(noPendingTimes + "");
            double margin = CountClass.getMargin(type, noPendingTimes, askBidOne, askBidTwo, selectWhatNoPended, marginBase, marginChange, usdprex);
            if (margin == -1) return;
//            tvMargin.setText("需资金:$" + margin + buyMax);
            tvMargin.setText("占用保证金:$" + margin + "美金");

            marginAll = margin;
        }
    }

    @OnClick({R.id.ll_buy_rise, R.id.ll_buy_fall})
    public void simpleTrande(View view) {
        switch (view.getId()) {
            case R.id.ll_buy_rise:
                if (activity.userId == -1) {
                    activity.noLoginGoThere();
                    return;
                }
                if (activity.userId == -1)
                    activity.noLoginGoThere();
                if (handMax != 0) {
                    if (quickOrderStatus)
                        presenter.wareHouse(SpUtils.getString(getContext(), "accessToken", ""), symbolK, SpUtils.getInt(getContext(), "userId"), 0, (float) noPendingTimes, tp, sl);
                    else
                        submitTraderOpenData(0);
                } else {
                    setPopupUnderMargin();
                }
                break;
            case R.id.ll_buy_fall:
                if (activity.userId == -1) {
                    activity.noLoginGoThere();
                    return;
                }
                if (handMax != 0) {
                    if (quickOrderStatus)
                        presenter.wareHouse(SpUtils.getString(getContext(), "accessToken", ""), symbolK, SpUtils.getInt(getContext(), "userId"), 1, (float) noPendingTimes, tp, sl);
                    else
                        submitTraderOpenData(1);

                } else {
                    //弹出资金不足提示框
                    setPopupUnderMargin();
                }
                break;
        }
    }

    /**
     * 实时数据，由Activity提供
     */
    public void setRealTimeDatas(List<RealTimeQuoteDatas.DataBean.QuoteBean> quoteBeen) {
        if (getActivity() == null) return;
        int quoteBeenSize = quoteBeen.size();
        if (quoteBeen != null && quoteBeenSize > 0) {
//            if (noTvBuyRise == null) return;
            for (int i = 0; i < quoteBeenSize; i++) {
                String curSymbol = quoteBeen.get(i).getSymbol();
                if (curSymbol.equals(symbolK)) {
                    ask = quoteBeen.get(i).getAsk();
                    bid = quoteBeen.get(i).getBid();
                    askBidOne = new double[]{ask, bid};
                }
                if (symbols != null && curSymbol.equals(symbols[1])) {
                    askBidTwo = new double[]{quoteBeen.get(i).getAsk(), quoteBeen.get(i).getBid()};
                }
                if (symbols != null && curSymbol.equals(symbols[2])) {
                    askBidThree = new double[]{quoteBeen.get(i).getAsk(), quoteBeen.get(i).getBid()};
                }
            }
//             else {
//                //用于展示页面上的的基本数据
//                ask = quoteBeen.get(0).getAsk();
//                bid = quoteBeen.get(0).getBid();
//                askBidOne = new double[]{ask, bid};
//            }


//            price = Arith.div(Arith.add(ask, bid), 2, digits);
//            if (noTvBuyRise != null)
//                noTvBuyRise.setText(ask + "");
//            if (noTvBuyFall != null)
//                noTvBuyFall.setText(bid + "");

            //当开启止盈止损时
//            if (isSetLoseOrProfit) {
//                if (selectWhatNoPended == 0) {
//                    //买入
//                    mStopProfit = Arith.add(bid, stopsLevel);
//                    mStopLoss = Arith.sub(bid, stopsLevel);
//                    noTVStopProfit.setText("≧ " + mStopProfit);
//                    noTVStopLoss.setText("≦ " + mStopLoss);
//                } else {
//                    //卖出
//                    mStopProfit = Arith.sub(ask, stopsLevel);
//                    mStopLoss = Arith.add(ask, stopsLevel);
//                    noTVStopLoss.setText("≧ " + mStopLoss);
//                    noTVStopProfit.setText("≦ " + mStopProfit);
//                }
//            }
//            if (tag == 0) {
//                double margin = getMargin();
            double margin2 = CountClass.getMargin(type, noPendingTimes, askBidOne, askBidTwo, selectWhatNoPended, marginBase, marginChange, usdprex);
            if (margin2 == -1) return;
            Logger.e("accAmt:", accAmt + "  margin2: " + margin2);
            if (accAmt > margin2) {
                double accAmt2 = Arith.round(Arith.mul(accAmt, 0.8), 2);
                handMax = Arith.div2(Arith.mul(accAmt2, noPendingTimes), margin2, 2);
                handMax = Arith.div(handMax, minVolume, 0);//处理最小手数不定的情况
                handMax = Arith.mul(handMax, minVolume);
                buyMax = "|余额最大可买:" + handMax + "手";
                noIVRightAdd.setEnabled(true);
            } else {
                buyMax = "|余额最大可买:" + 0 + "手";
                noIVRightAdd.setEnabled(false);
            }
            marginAll = margin2;
//            tvMargin.setText("需资金:$" + margin2 + buyMax);
            tvMargin.setText("占用保证金:$" + margin2 + "美金");

//                tag = 1;
//            }

        }
    }


    /**
     * 弹出资金不足提示框
     */
    private void setPopupUnderMargin() {
        View view = View.inflate(getContext(), R.layout.dialog_under_margin, null);
        TextView btnGoRecharge = (TextView) view.findViewById(R.id.btn_go_recharge);
        TextView btnEnsure = (TextView) view.findViewById(R.id.btn_ensure);
        btnGoRecharge.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getActivity(), RechargeActivity.class));
                popupWindow.dismiss();
            }
        });
        btnEnsure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        isFinishActivity = false;
        showPopupWindow(view);
    }

    /**
     * 开仓前提示
     */
    private void submitTraderOpenData(final int where) {
        View view = View.inflate(getContext(), R.layout.pop_style_sure_orders, null);
        TextView tvItemName = (TextView) view.findViewById(R.id.tv_item_name);
        TextView tvBuyRise = (TextView) view.findViewById(R.id.tv_buy_rise);
        TextView tvHandTimes = (TextView) view.findViewById(R.id.tv_hand_times);
        TextView tvStopProfit = (TextView) view.findViewById(R.id.tv_stop_profit);
        TextView tvStopLoss = (TextView) view.findViewById(R.id.tv_stop_loss);
        TextView btnSure = (TextView) view.findViewById(R.id.btn_go_order);
        TextView btnCancle = (TextView) view.findViewById(R.id.btn_cancel);
        TextView tvBuyStatus = (TextView) view.findViewById(R.id.tv_buy_status);
        TextView tvHandsAndName = (TextView) view.findViewById(R.id.tv_hands_money_name);
        btnSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (where == 0)
                    presenter.wareHouse(SpUtils.getString(getContext(), "accessToken", ""), symbolK, SpUtils.getInt(getContext(), "userId"), 0, (float) noPendingTimes, tp, sl);
                else if (where == 1)
                    presenter.wareHouse(SpUtils.getString(getContext(), "accessToken", ""), symbolK, SpUtils.getInt(getContext(), "userId"), 1, (float) noPendingTimes, tp, sl);
                else if (where == 2)
                    presenter.wareHouse(SpUtils.getString(getContext(), "accessToken", ""), symbolK, SpUtils.getInt(getContext(), "userId"), selectWhatNoPended, (float) noPendingTimes, tp, sl);

                playSound(true);
                popupWindow.dismiss();
            }
        });
        btnCancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

        tvItemName.setText(activity.symbolCn + " " + symbolK);
        switch (where) {
            case 0:
                tvBuyRise.setText("买涨：" + BaseUtils.getDigitsData(ask, digits));
                tvBuyStatus.setText("买涨");
                tvBuyStatus.setBackgroundResource(R.drawable.blue_text_bg);
                break;
            case 1:
                tvBuyRise.setText("买跌：" + BaseUtils.getDigitsData(bid, digits));
                tvBuyStatus.setText("买跌");
                tvBuyStatus.setBackgroundResource(R.drawable.orange_text_bg);
                break;
            case 2:
                if (selectWhatNoPended == 0) {
                    tvBuyRise.setText("买涨：" + BaseUtils.getDigitsData(ask, digits));
                    tvBuyStatus.setText("买涨");
                    tvBuyStatus.setBackgroundResource(R.drawable.yellow_text_bg);
                } else {
                    tvBuyRise.setText("买跌：" + BaseUtils.getDigitsData(bid, digits));
                    tvBuyStatus.setText("买跌");
                    tvBuyStatus.setBackgroundResource(R.drawable.green_text_bg);

                }
                break;
        }

        tvHandTimes.setText("占用：" + "$" + marginAll);
        tvHandsAndName.setText(" " + noPendingTimes + "手 " + activity.symbolCn);
        if (tp == 0) {
            tvStopProfit.setText("止盈：未设置");
        } else {
            tvStopProfit.setText("止盈：" + BaseUtils.getDigitsData(tp, digits));
        }
        if (sl == 0) {
            tvStopLoss.setText("止损：未设置");
        } else {
            tvStopLoss.setText("止损：" + BaseUtils.getDigitsData(sl, digits));

        }
        isFinishActivity = false;
        showPopupWindow(view);
    }

    private void playSound(boolean b) {

        int soundID;
        if (b) {
            soundID = soundPool.load(getActivity(), R.raw.open, 1);
        }else{
            soundID = soundPool.load(getActivity(), R.raw.close, 1);
        }

        soundPool.play(
                soundID,
                0.1f,      //左耳道音量【0~1】
                0.5f,      //右耳道音量【0~1】
                0,         //播放优先级【0表示最低优先级】
                0,         //循环模式【0表示循环一次，-1表示一直循环，其他表示数字+1表示当前数字对应的循环次数】
                1          //播放速度【1是正常，范围从0~2】
        );
    }

    /**
     * 显示操作对话框
     *
     * @param mainView
     */
    public void showPopupWindow(View mainView) {
        popupWindow = new PopupWindow(mainView, WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setAnimationStyle(R.style.AnimationBottonAndTop);
        popupWindow.showAtLocation(View.inflate(getContext(), R.layout.activity_stock_chart, null), Gravity.BOTTOM, 0, 0);
        setBackgroundAlpha(0.7f);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                setBackgroundAlpha(1f);
                if (runnable != null && handler != null) {
                    handler.removeCallbacks(runnable);
                }
                if (isFinishActivity)
                    getActivity().finish();

            }
        });

    }

    /**
     * 设置popupwindow背景色
     *
     * @param bgAlpha
     */
    public void setBackgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
        lp.alpha = bgAlpha;
        getActivity().getWindow().setAttributes(lp);
    }

    /**
     * 展示开仓成功后返回信息
     */
    private void setPopupTraderOpenSuccess(OpenTrader openTrader) {
        showTime = 5000;
        View view = View.inflate(getContext(), R.layout.pop_trade_result, null);//pop_style_order_success
        ImageView ivTradeStatus = (ImageView) view.findViewById(R.id.iv_trade_status);
        TextView tvChName = (TextView) view.findViewById(R.id.tv_ch_name);
        TextView tvEnName = (TextView) view.findViewById(R.id.tv_en_name);
        TextView tvValume = (TextView) view.findViewById(R.id.tv_valume);
        TextView tvTradePrice = (TextView) view.findViewById(R.id.tv_trade_price);
        tvChName.setText(openTrader.getSymbolCn());
        tvEnName.setText(openTrader.getSymbol());
        tvValume.setText(openTrader.getVolume() + "手");
        tvTradePrice.setText("开仓价：" + openTrader.getOpenPrice());
        if (openTrader.getCmd() == 0) {
            ivTradeStatus.setImageResource(R.mipmap.buy_icon);
        } else {
            ivTradeStatus.setImageResource(R.mipmap.sell_icon);
        }

        EventBus.getDefault().post(new EventDatas(EventContents.STOP_LOSS_OR_PROFIT_FINISH_TRADE, null));
        isFinishActivity = true;
        showPopupWindow(view);
        runnable = new Runnable() {
            @Override
            public void run() {
                showTime -= 1000;
                if (showTime == 0) {
                    handler.removeCallbacks(runnable);
                    popupWindow.dismiss();
                    getActivity().finish();

                } else
                    handler.postDelayed(runnable, 1000);
            }
        };
        handler.post(runnable);
    }
}
